#!/bin/sh

#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
#    This file is part of ICTP RegCM.
#    
#    Use of this source code is governed by an MIT-style license that can
#    be found in the LICENSE file or at
#
#         https://opensource.org/licenses/MIT.
#
#    ICTP RegCM is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
# Script that runs the NCL script diurnalaverages, which does diurnal averages
# of generic netcdf data 
#--Created 03/2011 for RegCMv4.1 by Travis A. O'Brien <tobrien@ucsc.edu>
#

#A subroutine for printing the proper usage to the screen
printusage ()
{
  echo "usage: $0  FILENAME.nc OUTFILENAME.nc"
  echo "  Where FILENAME.nc is an hourly netcdf file, with less than 6 total "
  echo "  dimensions, that should be averaged."
  echo "  "
  echo "  OUTFILENAME.nc is the output file name."
  exit
}

#Check if the Environment variable REGCMSRCDIR has been set
if [ -z "$REGCMSRCDIR" ]; then
  echo "Error: the environtment variable REGCMSRCDIR is not set.  Please set it to the base directory of your RegCM 4.1 source code: $REGCMSRCDIR"
  exit
fi

#TODO: Check validity and occurrence of command line arguments
if [ -z "$1" ]; then
  printusage
else
  INFILENAME=$1
fi
if [ ! -e "$INFILENAME" ]; then
  echo "Error: '${INFILENAME}' does not exist"
  printusage
fi
if [ -z "$2" ]; then
  printusage
else
  OUTFILENAME=$2
fi
if [ -z "$3" ]; then
  STARTHOUR=0
else
  STARTHOUR=$3
fi

echo "Diurnally averaging $INFILENAME..."

NCLBASE="" #Assume that the NCL binary directory is in the user's path
NCL="${NCLBASE}ncl"
DIURNALAVENCL="$REGCMSRCDIR/Tools/Scripts/NCL/diurnalaverager.ncl"

#Generate file names with quotes around them so that they can be passed to
#ncl
INFILE="\"${INFILENAME}\""
OUTFILE="\"${OUTFILENAME}\""

#Run NCL, giving it the file paths from above
$NCL $DIURNALAVENCL \
      "infilename=${INFILE}" \
      "outfilename=${OUTFILE}" \




